package com.sskj.one.mine;

import android.app.FragmentTransaction;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.bulong.rudeness.RudenessScreenHelper;
import com.hjq.toast.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.base.HttpData;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.adapter.BaseAdapter;
import com.sskj.lib.adapter.ViewHolder;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.one.R;
import com.sskj.one.bean.AgreeBean;
import com.sskj.one.bean.GouhuiBean;
import com.sskj.one.bean.TongdaoBean;
import com.sskj.one.component.DaggerUserDataComponent;
import com.sskj.one.login.VideoActivity;
import com.sskj.one.util.EditUtil;
import com.sskj.one.view.BottomDialog;
import com.zzhoujay.richtext.RichText;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.MaybeObserver;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * @author Hey
 * Create at  2019/05/22
 */
public class HuiActivity extends BaseActivity<HuiPresenter> {

    @BindView(R.id.smartRefreshView)
    SmartRefreshLayout smartRefreshView;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tv_now_rate)
    TextView tvNowRate;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_record)
    TextView tvRecord;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.et_jiehui)
    EditText etJiehui;
    @BindView(R.id.tv_money_gouhui)
    TextView tvMoneyGouhui;
    @BindView(R.id.ll_gouhui)
    LinearLayout llGouhui;
    @BindView(R.id.cb_wechat)
    CheckBox cbWechat;
    @BindView(R.id.cb_alipay)
    CheckBox cbAlipay;
    @BindView(R.id.cb_bank)
    CheckBox cbBank;
    @BindView(R.id.tv_msg_type)
    TextView tvMsgType;
    @BindView(R.id.tv_msg)
    TextView tvMsg;
    @BindView(R.id.tv_btn_type)
    TextView tvBtnType;
    @BindView(R.id.et_pay_pwd)
    EditText etPayPwd;
    @BindView(R.id.iv_see)
    ImageView ivSee;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.ll_pay_pwd)
    LinearLayout llPayPwd;
    @BindView(R.id.ll_jiehui)
    LinearLayout ll_jiehui;
    @BindView(R.id.ll_wechat)
    LinearLayout ll_wechat;
    @BindView(R.id.ll_alipay)
    LinearLayout ll_alipay;
    @BindView(R.id.ll_bank)
    LinearLayout ll_bank;
    @BindView(R.id.view_wechat)
    View view_wechat;
    @BindView(R.id.view_alipay)
    View view_alipay;
    @Inject
    UserViewModel userViewModel;

    private UserData userData;

    private String type;
    private String tongdao = "";//支付通道
    private String payway = "";//支付方式
    private String gouHuiMOney;//购汇金额
    private List<String> moneys = new ArrayList<>();

    private SlimAdapter<TongdaoBean> slimAdapter;

    private List<Integer> isCheck = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.app_activity_hui;
    }

    @Override
    public HuiPresenter getPresenter() {
        return new HuiPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        type = getIntent().getStringExtra("type");
        if (type.equals(Constans.GOU_HUI)) {
            tvTitle.setText("购汇");
            tvRecord.setText("购汇记录");
            tvType.setText("购汇金额");
            recyclerView.setVisibility(View.VISIBLE);
            ll_jiehui.setVisibility(View.GONE);
            llPayPwd.setVisibility(View.GONE);
            etJiehui.setVisibility(View.GONE);
            llGouhui.setVisibility(View.VISIBLE);
            tvMsgType.setText("购汇须知");
            tvBtnType.setText("立即购汇");
            mPresenter.getAgree("reg_agree");
        } else if (type.equals(Constans.JIE_HUI)) {
            tvTitle.setText("结汇");
            tvRecord.setText("结汇记录");
            tvType.setText("结汇金额");
            recyclerView.setVisibility(View.GONE);
            ll_jiehui.setVisibility(View.VISIBLE);
            llPayPwd.setVisibility(View.VISIBLE);
            etJiehui.setVisibility(View.VISIBLE);
            llGouhui.setVisibility(View.GONE);
            tvMsgType.setText("结汇须知");
            tvBtnType.setText("立即结汇");
            mPresenter.getAgree("trans_agree");
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setPaintColor(ContextCompat.getColor(this, R.color.divide))
                .setPaintWidth((int) RudenessScreenHelper.dp2px(this, 1))
                .setFirstDraw(false)
                .setLastDraw(false));
        Map<String, Integer> icons = new HashMap<>();
        icons.put("1", R.mipmap.icon_wechat);
        icons.put("2", R.mipmap.icon_alipay);
        icons.put("3", R.mipmap.icon_bank);
        slimAdapter = SlimAdapter.create().register(R.layout.item_tongdao, new SlimInjector<TongdaoBean>() {
            @Override
            public void onInject(TongdaoBean data, IViewInjector injector, List payloads) {
                injector.text(R.id.tv_tongdao, data.getP4_typeName())
                        .image(R.id.iv_tongdao, data.getP4_typeCode().equals("offline") ? R.mipmap.icon_xianxia : icons.get(data.getOrderlist()))
                        .image(R.id.cb_tongdao, isCheck.contains(slimAdapter.getData().indexOf(data)) ?
                                ContextCompat.getDrawable(HuiActivity.this, R.mipmap.icon_checked) : ContextCompat.getDrawable(HuiActivity.this, R.mipmap.icon_unchecked));
                injector.clicked(R.id.cb_tongdao, v -> {
                    if (isCheck.contains(slimAdapter.getData().indexOf(data))) {
                        return;
                    } else {
                        isCheck.clear();
                        isCheck.add(slimAdapter.getData().indexOf(data));
                        tongdao = data.getP4_typeCode();
                        injector.image(R.id.cb_tongdao, ContextCompat.getDrawable(HuiActivity.this, R.mipmap.icon_checked));
                        slimAdapter.notifyDataSetChanged();
                    }
                });
                injector.clicked(R.id.tv_jieshao, v -> {
                    if (data.getP4_typeCode().equals("offline")) {
                        VideoActivity.start(HuiActivity.this, Constans.VIDEO_OFFLINE);
                    } else if (data.getP4_typeCode().equals("bizhifu")) {
                        VideoActivity.start(HuiActivity.this, Constans.VIDEO_BIZHIFU);
                    }
                });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDate(CoinBean data) {
        if (data.getCode().equals("USDCNY")) {
            if (tvNowRate != null) {
                tvNowRate.setText(NumberUtil.keep(data.getPrice(), 5));
            }
        }
    }

    @Override
    public void initData() {
        if (type.equals(Constans.GOU_HUI)) {
            mPresenter.getRechargeInfo();
            mPresenter.getTongdaos(true);
        }
        smartRefreshView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                userViewModel.update();
                if (type.equals(Constans.GOU_HUI)) {
                    mPresenter.getRechargeInfo();
                    mPresenter.getTongdaos(true);
                } else {
                    smartRefreshView.finishRefresh();
                }
            }
        });

        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                tvMoney.setText("$" + NumberUtil.keep(userData.getUsable(), 5));
                if (type.equals(Constans.JIE_HUI)) {
                    ll_wechat.setVisibility(View.GONE);
                    ll_alipay.setVisibility(View.GONE);
                    ll_bank.setVisibility(View.GONE);
                    view_wechat.setVisibility(View.GONE);
                    view_alipay.setVisibility(View.GONE);
                    if (!isEmpty(userData.getAlipay_nums()) && isEmpty(userData.getBank_nums())) {
                        ll_alipay.setVisibility(View.VISIBLE);
                    } else if (isEmpty(userData.getAlipay_nums()) && !isEmpty(userData.getBank_nums())) {
                        ll_bank.setVisibility(View.VISIBLE);
                    } else if (!isEmpty(userData.getAlipay_nums()) && !isEmpty(userData.getBank_nums())) {
                        ll_alipay.setVisibility(View.VISIBLE);
                        ll_bank.setVisibility(View.VISIBLE);
                        view_alipay.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
        ClickUtil.click(300, ivSee, () -> {
            EditUtil.togglePs(etPayPwd, ivSee);
        });
        ClickUtil.click(300, llGouhui, () -> {
            BottomDialog.showShopCheck(this, moneys, tv -> {
                gouHuiMOney = tv;
                tvMoneyGouhui.setText("$ " + tv);
            });
        });
        ClickUtil.click(300, tvRecord, () -> {
            if (isEmpty(type)) {
                return;
            }
            RecordHuiActivity.start(HuiActivity.this, type);
        });

        ClickUtil.click(300, cbWechat, () -> {
            payway = Constans.GOUHUI_WECHAT;
            cbWechat.setChecked(true);
            cbAlipay.setChecked(false);
            cbBank.setChecked(false);
        });
        ClickUtil.click(300, cbAlipay, () -> {
            payway = Constans.GOU_HUI_ALIPAY;
            cbWechat.setChecked(false);
            cbAlipay.setChecked(true);
            cbBank.setChecked(false);
        });
        ClickUtil.click(300, cbBank, () -> {
            payway = Constans.GOUHUI_BANK;
            cbWechat.setChecked(false);
            cbAlipay.setChecked(false);
            cbBank.setChecked(true);
        });

        ClickUtil.click(300, tvBtnType, () -> {
            if (userData == null) {
                ToastUtils.show("获取用户信息失败");
                return;
            }
            if (type.equals(Constans.GOU_HUI)) {
                if (isEmpty(gouHuiMOney)) {
                    ToastUtils.show("请选择购汇金额");
                    return;
                }
                if (isEmpty(tongdao)) {
                    ToastUtils.show("请选择支付通道");
                    return;
                }
                if (tongdao.equals("offline")) {
                    DownGouhuiActivity.start(HuiActivity.this, tongdao, gouHuiMOney, getText(tvNowRate));
                    return;
                }
                mPresenter.createRechargeOrder(gouHuiMOney, tongdao);
            } else if (type.equals(Constans.JIE_HUI)) {
                if (isEmpty(etJiehui)) {
                    toastHint(etJiehui);
                    return;
                }
                if (isEmpty(etPayPwd)) {
                    toastHint(etPayPwd);
                    return;
                }
                if (isEmpty(payway)) {
                    ToastUtils.show("请选择支付方式");
                    return;
                }

                if (payway.equals(Constans.GOUHUI_BANK)) {
                    mPresenter.gouhui(getText(etJiehui),
                            getText(etPayPwd),
                            payway, userData.getBank_username(),
                            "", "",
                            userData.getBank_name(),
                            userData.getBank_sub_name(),
                            userData.getBank_nums());
                } else if (payway.equals(Constans.GOU_HUI_ALIPAY)) {
                    mPresenter.gouhui(getText(etJiehui), getText(etPayPwd), payway, userData.getAlipay_username(), "", userData.getAlipay_nums(), "", "", "");
                }
            }
        });
    }

    public void getAgreeOK(AgreeBean data) {
        if (data == null) {
            return;
        }
        RichText.fromHtml(formatImg(data.getInc_type())).into(tvMsg);
    }

    private String formatImg(String law_agree) {
        Document document = Jsoup.parse(law_agree);
        Elements imgs = document.getElementsByTag("img");
        for (Element img : imgs) {
            img.attr("width", "100%").attr("height", "auto");
            String url = img.attr("src");
            if (!url.contains("http")) {
                url = BaseHttpConfig.BASE_URL + url;
            }
            img.attr("src", url);
        }
        return document.toString();
    }

    public static void start(Context context, String type) {
        Intent intent = new Intent(context, HuiActivity.class);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    public void getChargeInfoOK(List<String> data) {
        if (data == null) {
            return;
        }
        if (data.size() > 0) {
            gouHuiMOney = data.get(0);
            tvMoneyGouhui.setText("$" + data.get(0));
        }
        this.moneys = data;
    }

    public void getTongdaosOK(List<TongdaoBean> data) {
        if (data == null) {
            return;
        }
        slimAdapter.updateData(data);
    }

    public void createRechargeOK(GouhuiBean data) {
        if (data == null) {
            return;
        }
        if (tongdao.equals("tongdao001")) {
        }
        if (data.getZftd().equals("yimafu")) {
            String url = data.getUrl();
            url = "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n</head>\n<body>\n" + url;
            url = url + "\n</body>\n</html>";
            WebH5Activity.start(HuiActivity.this, "购汇", url, true);
        } else if (data.getZftd().equals("tongdao001") || data.getZftd().equals("tongdao002")) {
            WebH5Activity.start(HuiActivity.this, "购汇", data.getUrl(), true);
        } else {
            WebH5Activity.start(HuiActivity.this, "购汇", data.getUrl(), false);
        }
    }

    public void stopRefresh() {
        if (smartRefreshView != null && smartRefreshView.isRefreshing()) {
            smartRefreshView.finishRefresh();
        }
    }

    public void gouhuiOK() {
        etPayPwd.getText().clear();
        ToastUtils.show("结汇成功");
        RecordHuiActivity.start(HuiActivity.this, type);
        userViewModel.update();
    }
}
